package com.gitee.hermer.boot.jee.upms.shiro;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.gitee.hermer.boot.jee.upms.shiro.users.domain.AccountUser;
import com.gitee.hermer.boot.jee.upms.shiro.users.domain.SystemResource;
import com.gitee.hermer.boot.jee.upms.shiro.users.service.impl.AccountUserServiceImpl;
import com.gitee.hermer.boot.jee.upms.shiro.users.service.impl.SystemResourceServiceImpl;



public class BootShiroRealm extends AuthorizingRealm {

	@Autowired
	private AccountUserServiceImpl userService;

	@Autowired
	private SystemResourceServiceImpl resourceService;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		AccountUser user= (AccountUser) SecurityUtils.getSubject().getPrincipal();

		List<SystemResource> resourcesList = resourceService.listAccountResources(new SystemResource(user.getId()));
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		for(SystemResource resources: resourcesList){
			info.addStringPermission(resources.getResourceUrl());
		}
		return info;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken arg0) throws AuthenticationException {

		String username = (String)arg0.getPrincipal();
		AccountUser t = new AccountUser();
		t.setUserName(username);
		AccountUser user;
		try {
			user = userService.find(t);
		} catch (Throwable e) {
			throw new UnknownAccountException();
		}
		if(user==null) throw new UnknownAccountException();
		if (0==user.getEnable()) {
			throw new LockedAccountException(); // 帐号锁定
		}
		SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
				user, //用户
				user.getPassword(), //密码
				ByteSource.Util.bytes(username),
				getName()  //realm name
				);
		// 当验证都通过后，把用户信息放在session里
		Session session = SecurityUtils.getSubject().getSession();
		session.setAttribute("userSession", user);
		session.setAttribute("userSessionId", user.getId());
		return authenticationInfo;
	}

}
